package model.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import DAO.HibernateUtil;
import DAO.TrainDAO;
import DAO.impl.TrainDAOImpl;
import DTO.DTOManager;
import DTO.TrainDTO;

/**
 * Class that implements the model.Train interface.
 */
public class TrainImpl implements model.Train {

	private TrainDAO trainDAO = new TrainDAOImpl();

	private Logger logger = LoggerFactory.getLogger("TrainImpl");
	
	private DTOManager dtoManager = new DTOManager();

	/**
	 * This method checks if there is a train in DB which has the same 
	 * DTO implementation as the given DTO. If it is NOT found in DB, method 
	 * creates a new Train entity from DTO and saves it.
	 * 
	 * @param trainDTO - DTO of train which is required to be removed
	
	 */
	@Override
	public void saveUniqueTrain(TrainDTO trainDTO) {
		try {
			HibernateUtil.beginTransaction();
			if (this.trainDAO.findTrainByTrainNumber(trainDTO
					.getTrainNumber()) == null) {
				Train train = this.dtoManager.createNewTrainFromDTO(trainDTO);
				this.trainDAO.save(train);
			}
			HibernateUtil.commitTransaction();
		} catch (HibernateException e) {
			this.logger.error("Error in save unique train "
													+ e.getLocalizedMessage());
			HibernateUtil.rollbackTransaction();
		} 
	}

	/**
	 * This method checks if there is a train in DB which has the same 
	 * DTO implementation as given DTO. If it is found in DB, method 
	 * removes it.
	 * 
	 * @param trainDTO - DTO of train which is required to be removed
	
	 */
	@Override
	public void removeUniqueTrain(TrainDTO trainDTO) {
		try {
			HibernateUtil.beginTransaction();
			Train train = this.trainDAO.findTrainByTrainNumber
					(trainDTO.getTrainNumber());
			if (train != null) {
				this.trainDAO.delete(train);
			}
			HibernateUtil.commitTransaction();
		} catch (HibernateException e) {
			this.logger.error("Error in remove unique train " 
											+ e.getLocalizedMessage());
			HibernateUtil.rollbackTransaction();
		} 
	}

	/**
	 * Method looks for all the Train entities in DB.
	 * 
	 * @return	- List of all Train entities in DB or null if there is no
	 * 			  train in DB.
	 */
	@Override
	public List<model.impl.Train> findAll() {
		List<model.impl.Train> trains = null;
		try {
			HibernateUtil.beginTransaction();
			trains = this.trainDAO.findAll(model.impl.Train.class);
			HibernateUtil.commitTransaction();
		} catch (HibernateException e) {
			this.logger.error("Error in find all trains " 
												+ e.getLocalizedMessage());
			HibernateUtil.rollbackTransaction();
		} 
		return trains;
	}
}
